package com.ruoyi.merchant.aspect;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.IPage;
import com.ruoyi.common.core.enums.CMSConstants;
import com.ruoyi.common.core.enums.DataTypeEnum;
import com.ruoyi.common.core.utils.ConvertUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.merchant.annotation.Dict;
import com.ruoyi.merchant.annotation.DictFilter;
import com.ruoyi.merchant.annotation.Element;
import com.ruoyi.merchant.service.DictService;
import com.ruoyi.merchant.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 字典aop类
 * @Author: dangzhenghui
 * @Date: 2019-3-17 21:50
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class DictAspect {

    @Autowired
    private DictService dictService;

    @Autowired
    private RedisService redisService;

    // 定义切点Pointcut
    @Pointcut("@annotation(com.ruoyi.merchant.annotation.DictFilter)")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        DictFilter df = method.getAnnotation(DictFilter.class);
        String dataType = df.dataType();
    	long time1=System.currentTimeMillis();	
        Object result = pjp.proceed();
        long time2=System.currentTimeMillis();
        log.debug("获取JSON数据 耗时："+(time2-time1)+"ms");
        long start=System.currentTimeMillis();
        dealResult(result,dataType);
        long end=System.currentTimeMillis();
        log.debug("解析注入JSON数据  耗时"+(end-start)+"ms");
        return result;
    }

    /**
     * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
     * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ，table字典 code table text配合使用与原来jeecg的用法相同
     * 示例为SysUser   字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text，已字段名称加_dictText形式返回到前端
     * 例输入当前返回值的就会多出一个sex_dictText字段
     * {
     *      sex:1,
     *      sex_dictText:"男"
     * }
     * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
     *  customRender:function (text) {
     *               if(text==1){
     *                 return "男";
     *               }else if(text==2){
     *                 return "女";
     *               }else{
     *                 return text;
     *               }
     *             }
     *             目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
     * @param result
     */
    private void dealResult(Object result,String dataType){
//        if (result instanceof TableDataInfo) {
            if (dataType.equals(DataTypeEnum.PAGE.getCode())) {
                if (((TableDataInfo) result).getCode() == 200 && ((TableDataInfo) result).getRows() instanceof List) {
                    Object record = (((TableDataInfo) result).getRows());
                    List<JSONObject> o = ( List<JSONObject> )parseDictText(record,dataType,null);
                    ((TableDataInfo) result).setRows(o);
                }
            }else if (dataType.equals(DataTypeEnum.LIST.getCode())){
                if (((AjaxResult) result).isSuccess() && ((AjaxResult) result).getData() instanceof List) {
                    Object record = ((AjaxResult) result).getData();
                    List<JSONObject> o = ( List<JSONObject> )parseDictText(record,dataType,null);
                    ((AjaxResult) result).setData(o);
                }
            }else if (dataType.equals(DataTypeEnum.ITEM.getCode())){
                if (((AjaxResult) result).isSuccess() && ((AjaxResult) result).getData() instanceof Object) {
                    Object record = ((AjaxResult) result).getData();
                    JSONObject o = (JSONObject)parseDictText(record,dataType,null);
                    ((AjaxResult) result).setData(o);
                }
            }

//        }
    }

    private Object parseDictText(Object result,String dataType,Class cls ) {
        if (dataType.equals(DataTypeEnum.PAGE.getCode()) || dataType.equals(DataTypeEnum.LIST.getCode())){
            if (result instanceof List) {
                List<JSONObject> items = new ArrayList<>();
                for (Object record : (List) result) {
                    ObjectMapper mapper = new ObjectMapper();
                    String json = "{}";
                    try {
                        //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                        json = mapper.writeValueAsString(record);
                    } catch (JsonProcessingException e) {
                        log.error("json解析失败" + e.getMessage(), e);
                    }
                    JSONObject item = JSONObject.parseObject(json);
                    covertItem(item, record,cls);
                    items.add(item);
                }
                return items;
            }
        }else if (dataType.equals(DataTypeEnum.ITEM.getCode())){
            if (result instanceof Object) {
                Object record = result;
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException e) {
                    log.error("json解析失败" + e.getMessage(), e);
                }
                JSONObject item = JSONObject.parseObject(json);
                covertItem(item, record,cls);
                return item;
            }
        }
        return null;
    }


    private void covertItem(JSONObject item,Object record,Class cls){
        //update-begin--Author:scott -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
        //for (Field field : record.getClass().getDeclaredFields()) {
        //转换类型
        if (cls != null){
            ObjectMapper objectMapper = new ObjectMapper();
            record = objectMapper.convertValue(record, cls);
        }
        for (Field field : ConvertUtils.getAllFields(record)) {
            //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String key = String.valueOf(item.get(field.getName()));

                //翻译字典值对应的txt
                String textValue = translateDictValue(code, text, table, key);

                log.debug(" 字典Val : "+ textValue);
                log.debug(" __翻译字典字段__ "+field.getName() + CMSConstants.DICT_TEXT_SUFFIX+"： "+ textValue);
                item.put(field.getName() + CMSConstants.DICT_TEXT_SUFFIX, textValue);
            }
            //子对象转化数据字典
            if (field.getAnnotation(Element.class) != null){
                String dataType = field.getAnnotation(Element.class).dataType();
                Class clsz = field.getAnnotation(Element.class).cls();
                Object obj = (Object)item.get(field.getName());
                Object result = parseDictText(obj,dataType,clsz);
                item.put(field.getName(),result);
            }
        }
    }

    /**
     *  翻译字典文本
     * @param code
     * @param text
     * @param table
     * @param key
     * @return
     */
    private String translateDictValue(String code, String text, String table, String key) {
    	if(StringUtils.isBlank(key)) {
    		return null;
    	}
        StringBuffer textValue=new StringBuffer();
        String[] keys = key.split(",");
        for (String k : keys) {
            String tmpValue = "";
            log.debug(" 字典 key : "+ k);
            if (k.trim().length() == 0) {
                continue; //跳过循环
            }
            if (!StringUtils.isEmpty(table)){
                String keyString = String.format("SimpleKey[%s,%s,%s,%s]",table,text,code,k.trim());
//                    final Object o = redisService.getCacheObject(keyString);
//                    tmpValue = o == null ?"":o.toString();
                if (StringUtils.isBlank(tmpValue)){
                    tmpValue= dictService.queryTableDictTextByKey(table,text,code,k.trim());
                    redisService.setCacheObject(keyString,tmpValue,24L, TimeUnit.HOURS);
                }
            }else {
                String keyString = String.format("SimpleKey[%s,%s]", code, k.trim());
//                    final Object o = redisService.getCacheObject(keyString);
//                    tmpValue = o == null ?"":o.toString();
                if (StringUtils.isBlank(tmpValue)){
                    tmpValue = dictService.queryDictTextByKey(code, k.trim());
                    redisService.setCacheObject(keyString,tmpValue,24L, TimeUnit.HOURS);
                }
            }
            if (tmpValue != null) {
                if (!"".equals(textValue.toString())) {
                    textValue.append(",");
                }
                textValue.append(tmpValue);
            }

        }
        return textValue.toString();
    }

}
